using System;
using UnityEngine;

namespace Framework
{
    public static class ColorUtil
    {
        public static Color Hex(string hex)
        {
            hex = hex?.Replace("#", "").Replace("0x", "").Trim() ?? "";
            if (hex.Length == 3) hex = $"{hex[0]}{hex[0]}{hex[1]}{hex[1]}{hex[2]}{hex[2]}FF";
            else if (hex.Length == 4) hex = $"{hex[0]}{hex[0]}{hex[1]}{hex[1]}{hex[2]}{hex[2]}{hex[3]}{hex[3]}";
            else if (hex.Length == 6) hex = $"{hex}FF";
            else if (hex.Length == 8) { }
            else throw new Exception("Invalid hex format");
            
            uint hexValue = uint.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            byte r = (byte)((hexValue >> 24) & 0xFF);
            byte g = (byte)((hexValue >> 16) & 0xFF);
            byte b = (byte)((hexValue >> 8) & 0xFF);
            byte a = (byte)((hexValue >> 0) & 0xFF);
            return new Color32(r, g, b, a);
        }
        
        public static Color Alpha(this Color color, float alpha) => new Color (color.r, color.g, color.b, Mathf.Clamp01(alpha));

        public static Color AdjustHSV(this Color color, float h = 0, float s = 0, float v = 0)
        {
            Color.RGBToHSV(color, out float H, out float S, out float V);
            H = Mathf.Repeat(H + h, 1f);
            S = Mathf.Clamp01(S + s);
            V = Mathf.Clamp01(V + v);
            return Color.HSVToRGB(H, S, V).Alpha(color.a);
        }
    }
}